import { Injectable,ChangeDetectorRef } from '@angular/core';
import { BaseService } from '../core/data/BaseService';
import { DataService } from '../core/data/DataService';
import { FormObject } from '../form/FormObject';
import { LoadingController } from 'ionic-angular';
/**
 * 添加用户导航器，方便其他的功能使用
 */
import { NavController,AlertController } from 'ionic-angular';

// 定义工作流的基础实现类，实现基础数据
@Injectable()
export class BpmObject extends FormObject {

    
    constructor(
		public dataService:DataService,
        public baseService:BaseService,
        public changeDetectorRef:ChangeDetectorRef,
        public navCtrl: NavController,
        public alert:AlertController,
        public loadingCtrl: LoadingController,
		) { 
            super(dataService,baseService,changeDetectorRef,loadingCtrl);
    }

    /**
     * 是否使用页面
     */
    public usePage=false;

    /**
     * 当前用户信息
     */
    public user:any={};

     //此处用来定义工作流里面的信息
    /**
     * 数据主键
     */
    public id:string="";

    /**
     * 表单（单页面应用中的主页面）
     */
    public viewId:string="";

    /**
     * 流程实例
     */
    public sexeid:string="";

    /**
     * 当前环节id
     */
    public cTaskId:string="";
    /**
     * 当前tab项
     */
    public ctab:string="";
    /**
     * 当前环节名称
     */
    public cTaskName:string="";
    /**
     * 流程授权
     */
    public auth:any={};
    /**
     * 已执行结束的tab
     */
    public tabs:any={};

    /**
     * 已执行结束的tab
     */
    public bpmKey:string="";

    /**
     * 定义流程中的过程事项
     */
    public process:any={};

    /**
     * 定义一下项目授权
     */
    public proauth:any={};

    /**
     * 用户提交操作验证
     */
    public opttj:any={};

    /**
     * 退回要素
     */
    public optback:any={};

    /**
     * 办理过程
     */
    public historyLst=[];

    public loadImage:string="";

    /**
     * 提取办理过程
     */
    loadBpmProcess(){
        var where={};
        where["sexeid:="]=this.sexeid;
        var order={};
        order["opttime"]=0;

        let imagepath= this.baseService.baseUrl+"/processImage/loadImage?bpmkey="+this.bpmKey;
        if(this.sexeid!=null && this.sexeid!='undefined' && this.sexeid!=''){
            imagepath=imagepath+"&sexeid="+this.sexeid;
        }
        this.loadImage=imagepath+"&uuid="+this.getGUID();
        this.dataService.getEntitys("bpmhistory",null,where,order,10000,1).subscribe((data)=>{
            if(data!=null && data.length>0){
                for (let item = 0; item < data.length; item++) {
                    data[item].icon='ios-arrow-forward';
                }
            }
            if(data!=null && data.length>0){
                this.historyLst=data;
            }else{
                this.historyLst=[];
            }
            
            
        });
    };
    

    /**
     * 查找数据服务
     */
    findWork(sn: string,success:Function,error:Function){
        /**
         * 暂时不处理用户信息
         */
        let user={};

        let loading = this.loadingCtrl.create({
            content: '数据加载中，请稍后...'//数据加载中显示
        });
        loading.present();
        if(sn==null){
            sn=this.sn;
        }

        this.dataService.findWork(sn,this.id,this.bpmKey,user).subscribe((data)=>{
            //$state.go(data.viewId);
            setTimeout(function(){
                loading.dismiss();
            },300);
          
            if(data.entity!=null){
                this.editRow=data.entity;
            }
            this.bpmKey=data.bpmKey;
            this.viewId=data.viewId;
            this.sexeid=data.sexeid;
            this.cTaskId=data.cTaskId;
            this.ctab=data.ctab;
            this.cTaskName=data.cTaskName;
            this.id=data.id;
            if(data.auth!=null){
                this.auth=data.auth;
            }else{
                this.auth={};
            }
            
            this.tabs={};
            if(data.tabs!=null){
                for(let k=0;k<data.tabs.length;k++){
                    //this.tabs[data.tabs[k]]=true;
                    let tabArr = data.tabs[k].split(",");
                    for(let i= 0;i<tabArr.length;i++){
                        this.tabs[tabArr[i]]=true;
                    }
                }
            }
            if(data.ctab!=null){
                let ctabArr = data.ctab.split(",");
                for(let k= 0; k<ctabArr.length;k++){
                    this.tabs[ctabArr[k]]=true;
                }
                //$rootScope.setTab(fName,ctabArr[0]);
                this.toView(ctabArr[0]);
            }
            //构建签批历史子表信息
            this.process={};
            if(data.multiTask!=null && data.multiTask.length>0){
                for(let k=0;k<data.multiTask.length;k++){
                    let item=data.multiTask[k];
                    this.process[item.taskdefinedid]=item;
                }
            }
            
            if(data.universalTask!=null && data.universalTask.length>0){
                for(let k=0;k<data.universalTask.length;k++){
                    let item=data.universalTask[k];
                    this.process[item.taskdefinedid]=item;
                }
            }
            this.proauth={};
            if(data.prjshow!=null && data.prjshow.length>0){
                let lst=data.prjshow.split(",");
                for(let k=0;k<lst.length;k++){
                    this.proauth[lst[k]]=true;
                }
            }
            this.changeDetectorRef.markForCheck();
            this.changeDetectorRef.detectChanges();

            if(success){
                success(this);
            }
        });
    };

    /**
     * 
     * @param tabId 切换工作流中的tab选项卡
     */
    setBpmTab(tabId){
        if(this.tabs!=null && this.tabs[tabId]){
            //$rootScope.setTab(fName,tabId);
            //TODO 功能待实现
        }
    };

    /**
     * 流程提交之前的验证
     * @param {Object} fName
     */
    bpmValidate(){
        let findTask=false;
        if(this.opttj.optiontype=='EndSign'){
            findTask=true;
        }
        for(let k=0;k<this.opttj.nextTask.length;k++){
            let ktask=this.opttj.nextTask[k];
            if(!ktask.taskSelect) continue;
            findTask=true;
            let unfind=true;
            for(let i=0;i<ktask.user.length;i++){
                if(ktask.user[i].userSelected){
                    unfind=false;
                }
            }
            if(unfind){
                // $.messager.alert("系统提示","节点"+ktask.taskName+"没有选择签批人");
                //TODO 提示功能按钮
                return false;
            }
        }
        if(!findTask){
                // $.messager.alert("系统提示","请选择需要提交的下一个环节");
                //TODO 提示功能按钮
                return false;
        }
        return true;
    };

    /**
     * 保存草稿
     */
    bpmSave(sn: string,success:Function,error:Function){

        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        this.isOpting=true;
        let optsave={};
        optsave["sexeid"]=this.sexeid;
        optsave["editHistory"]=[];
        optsave["bpmkey"]=this.bpmKey;
        //fo.optdisposal.id=fo.id;

        if(sn==null){
            sn=this.sn;
        }
       
        optsave["editHistory"]=this.createEditHistory();
        this.dataService.bpmSave(sn,optsave,this.editRow,this.user).subscribe((data)=>{
            this.isOpting=false;
            if(data.status){			
                if(data.entity!=null){
                    data.entity[this.isNew]=false;
                    this.editRow= data.entity;
                }
                this.changeDetectorRef.markForCheck();
                this.changeDetectorRef.detectChanges();
                if(success){
                    success(this);
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"保存成功！",
                        buttons:["确定"]
                      }).present();
                }
            }else{
                if(error){
                    error(); 
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"保存失败，请重试！",
                        buttons:["确定"]
                      }).present();
                }
            }
        });
    };

    update(sn: string,success:Function,error:Function){
        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        this.isOpting=true;

        if(sn==null){
            sn=this.sn;
        }
       
        this.dataService.update(sn,this.editRow).subscribe((data)=>{
            this.isOpting=false;
            if(data){
                if(success){
                    success(this);
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"保存成功！",
                        buttons:["确定"]
                      }).present();
                }
            }else{
                if(error){
                    error(); 
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"保存失败，请重试！",
                        buttons:["确定"]
                      }).present();
                }
            }
        });
    };

    showNextTaskSelect(sn: string,success:Function,error:Function,data:any){
        if(data.entity!=null){
            data.entity[this.isNew]=false;
            this.editRow=data.entity
            delete data.entity;
        }
        if(sn==null){
            sn=this.sn;
        }
        
        this.opttj={};
        if(data!=null){
            this.opttj=data;
        }else{
            this.opttj={}; 
        }
        
        this.editRow.sexeid=data.sexeid;
        this.sexeid=data.sexeid;
        this.opttj.selectTask=false;
        if(data.optiontype=='InclusiveSign' || data.optiontype=='ExclusiveSign'){
            this.opttj.selectTask=true;
        }

        if(!this.usePage){
            if(this.opttj.nextTask!=null && this.opttj.nextTask.length>0){

                this.selectTjTask(this.opttj.nextTask[0]);
                let alert = this.alert.create();
                alert.setTitle(this.opttj.nextTask[0].taskName);

                for(let k=0;k<this.opttj.nextTask[0].user.length;k++){
                    let iuser=this.opttj.nextTask[0].user[k];
                    alert.addInput({
                        type: 'checkbox',
                        label: iuser.userName,
                        value: iuser.userId,
                        checked: true
                    });
                    
                }
                alert.addButton('取消');
                alert.addButton({
                text: '确定',
                handler: data => {
                    console.log('Checkbox data:', data);
                    //this.testCheckboxOpen = false;
                   // this.testCheckboxResult = data;
                        if(data!=null && data.length>0){
                            for(let j=0;j<this.opttj.nextTask[0].user.length;j++){
                                this.opttj.nextTask[0].user[j].userSelected=false;
                                for(let i=0;i<data.length;i++){
                                    if(this.opttj.nextTask[0].user[j].userId==data[i]){
                                        this.opttj.nextTask[0].user[j].userSelected=true;
                                    }
                                }
                            }

                            if(!this.bpmValidate()){
                                /*let tempAlert= this.alert.create({
                                    title: '系统提示!',
                                    subTitle: '请先选择签批人!',
                                    buttons: ['确定']
                                });
                                tempAlert.present();*/

                                let confirm =this.alert.create({
                                    title: '系统提示',
                                    message: "请先选择签批人！",
                                    buttons: [
                                      {
                                        text: '确定',
                                        handler: () => {
                                         // console.log('Disagree clicked');
                                         this.showNextTaskSelect(sn,success,error,data);
                                        }
                                      }
                                    ]
                                  });
                                  confirm.present();

                            }else{
                                this.signTask(sn,null,null);
                            }
                        }else{
                            /*let tempAlert= this.alert.create({
                                title: '系统提示!',
                                subTitle: '请先选择签批人!',
                                buttons: ['确定']
                            });
                            tempAlert.present();*/

                            let confirm =this.alert.create({
                                title: '系统提示',
                                message: "请先选择签批人！",
                                buttons: [
                                  {
                                    text: '确定',
                                    handler: () => {
                                     // console.log('Disagree clicked');
                                     //alert.present();
                                     this.showNextTaskSelect(sn,success,error,data);
                                    }
                                  }
                                ]
                              });
                              confirm.present();
                        }
                   
                    }
                });
                alert.present();
            }else{
                let confirm=this.alert.create({
                    title: '系统提示?',
                    message: '确定提交?',
                    buttons: [
                      {
                        text: '取消',
                        handler: () => {
                          console.log('Disagree clicked');
                        }
                      },
                      {
                        text: '确定',
                        handler: () => {
                          //console.log('Agree clicked');
                          this.signTask(sn,null,null);
                        }
                      }
                    ]
                  });
                  confirm.present();
            }
        }


        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();

        if(success){
            success(this);
        }
    }

    /**
     * 获取项目的下一个环节
     */
    getNextTask(sn: string,success:Function,error:Function){
        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        if(sn==null){
            sn=this.sn;
        }
        this.isOpting=true;
        let editHistory=[];
        editHistory=this.createEditHistory();
        this.dataService.getNextTask(sn,this.bpmKey,this.editRow,editHistory,this.user).subscribe((data)=>{
            this.isOpting=false;
            this.showNextTaskSelect(sn,success,error,data);
        });
    };

    /**
     * 项目提交通过到下一个环节
     */
    signTask(sn: string,success:Function,error:Function){
        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        if(sn==null){
            sn=this.sn;
        }
        this.isOpting=true;
        this.opttj.editHistory=[];
        this.opttj.editHistory=this.createEditHistory();
        this.dataService.signTask(sn,this.opttj,this.editRow,this.user).subscribe((data)=>{
            this.isOpting=false;
            if(data.status){
                if(data.entity!=null){
                    data.entity[this.isNew]=false;
                    this.editRow= data.entity;
                   // delete data.entity;
                }
                this.changeDetectorRef.markForCheck();
                this.changeDetectorRef.detectChanges();
                if(success){
                    success(this);
                }

                this.goHome();
            }else{
                if(error){
                    error(); 
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"提交失败，请重试！",
                        buttons:["确定"]
                      }).present();
                }
            }
        });
    }

    /**
     * 选择提交节点
     * @param iTask 选择提交节点
     */
    selectTjTask(iTask:any){
        let opttj=this.opttj;
        let selected=iTask.taskSelect;
        //平行选择节点
        if(opttj.optiontype=='InclusiveSign'){
            for(let k=0;k<iTask.user.length;k++){
                if(selected){
                    iTask.user[k].userSelected=true;
                }else{
                    iTask.user[k].userSelected=false;
                }
            }
        }else if(opttj.optiontype=='ExclusiveSign'){
            if(selected){
                for(let j=0;j<opttj.nextTask.length;j++){
                    opttj.nextTask[j].taskSelect=false;
                    for(let k=0;k<opttj.nextTask[j].user.length;k++){
                        opttj.nextTask[j].user[k].userSelected=false;
                    }
                }
                iTask.taskSelect=true;
                for(let k=0;k<iTask.user.length;k++){
                    iTask.user[k].userSelected=true;
                }
            }else{
                //强制必须选择一个
                iTask.taskSelect=true;
            }
        }
                    
    };
    /**
     * 选择退回节点
     * @param iTask 
     */
    selectBackTask(iTask:any){
        let optback=this.optback;
        let selected=iTask.taskSelect;
        if(optback.optiontype=='ExclusiveSign'){
            if(selected){
                for(let j=0;j<optback.nextTask.length;j++){
                    optback.nextTask[j].taskSelect=false;
                }
                iTask.taskSelect=true;
            }else{
                //强制必须选择一个
                iTask.taskSelect=true;
            }
        }
    };

    /**
     * 提交通过时选择用户问题
     * @param iTask 
     * @param user 
     */
    selectTjUser(iTask:any,user:any){
        var selected=user.userSelected;
        var opttj=this.opttj;
        if(selected){
            iTask.taskSelect=true;
            if(opttj.optiontype=='ExclusiveSign'){
                for(var j=0;j<opttj.nextTask.length;j++){
                    if(iTask.taskdefinedid!=opttj.nextTask[j].taskdefinedid){
                        opttj.nextTask[j].taskSelect=false;
                        for(var k=0;k<opttj.nextTask[j].user.length;k++){
                            opttj.nextTask[j].user[k].userSelected=false;
                        }
                    }
                }
            }
        }else{
            
            if(opttj.optiontype=='InclusiveSign'){
                var finduser=false;
                for(var l=0;l<iTask.user.length;l++){
                    if(iTask.user[l].userSelected){
                        finduser=true;
                    }
                }
                if(!finduser){
                    iTask.taskSelect=false;
                }
            }
        }
    };

    /**
     * 返回主页面功能
     */
    goHome(){
       // this.navCtrl.push(TabsPage);
       this.navCtrl.pop();
    };

    /**
     * 定位到指定页面点
     * @param id 
     */
    toView(id:string){
        setTimeout(function(){
            let element = document.getElementById(id);
            if(element){
              element.scrollIntoView();
            }
        },300);
    };

    /**
     * 获取项目的退回环节
     */
    getBackTask(sn: string,success:Function,error:Function){
        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        if(sn==null){
            sn=this.sn;
        }
        this.isOpting=true;
        let editHistory=this.createEditHistory();
        this.dataService.getBackTask(sn,this.bpmKey,this.editRow,editHistory,this.user).subscribe((data)=>{
           this.isOpting=false;
            if(data.entity!=null){
                data.entity[this.isNew]=false;
                this.editRow=data.entity
                delete data.entity;
            }
            
            this.optback={};
            this.editRow.sexeid=data.sexeid;
            this.sexeid=data.sexeid;

            if(data.nextTask==null || data.nextTask.length<1){
                this.alert.create({
                    title:"系统提示",
                    message:"没有退回节点!",
                    buttons:[{
                      text:"确定",
                      role:"确定",
                      handler:()=>{
                          if(this.usePage){
                            this.navCtrl.pop();
                          }else{
                              return;
                          }
                      }
                    }]
                  }).present();
                return;
            }
            if(data!=null){
                this.optback=data;
            }else{
                this.optback={};
            }
        
            if(data.optiontype=='ExclusiveBack'){
                this.optback.selectTask=true;	
            }else{
                this.optback.selectTask=false;	
            }

            if(!this.usePage){
                if(this.optback.nextTask!=null && this.optback.nextTask.length>0){
                    //this.selectBackTask(this.optback.nextTask[0]);
                    if(this.optback.nextTask.length==1){
                        let confirm=this.alert.create({
                            title: '系统提示?',
                            message: '确定退回'+this.optback.nextTask[0].taskName+'?',
                            buttons: [
                              {
                                text: '取消',
                                handler: () => {
                                  console.log('Disagree clicked');
                                }
                              },
                              {
                                text: '确定',
                                handler: () => {
                                    this.sendBack(sn,null,null);
                                }
                              }
                            ]
                          });
                          confirm.present();
                        
                    }else{
                        let alert = this.alert.create();
                        alert.setTitle("退回");
                        for(let k=0;k<this.optback.nextTask.length;k++){
                            let task=this.optback.nextTask[k];
                            if(k<1){
                                alert.addInput({
                                    type: 'radio',
                                    label: task.taskName,
                                    value: task.taskdefinedid,
                                    checked: true
                                });
                            }else{
                                alert.addInput({
                                    type: 'radio',
                                    label: task.taskName,
                                    value: task.taskdefinedid
                                });
                            }
                            
                            
                        }
                        alert.addButton('取消');
                        alert.addButton({
                        text: '确定',
                        handler: data => {
                            console.log('radio data:', data);
            
                                if(data!=null && data.length>0){
                                    for(let j=0;j<this.optback.nextTask.length;j++){
                                        this.optback.nextTask[j].taskSelect=false;
                                        for(let i=0;i<data.length;i++){
                                            if(this.optback.nextTask[j].taskdefinedid==data[i]){
                                                //this.opttj.nextTask[j].taskSelect=true;
                                                this.selectBackTask(this.optback.nextTask[j]);
                                            }
                                        }
                                    }
                                    this.sendBack(sn,null,null);
                                   
                                }else{
                                    let tempAlert= this.alert.create({
                                        title: '系统提示!',
                                        subTitle: '请先退回环节!',
                                        buttons: ['确定']
                                    });
                                    tempAlert.present();
                                }
                           
                            }
                        });
                        alert.present();
                    }

                    
                }else{
                    let tempAlert= this.alert.create({
                        title: '系统提示!',
                        subTitle: '无可退回环节!',
                        buttons: ['确定']
                    });
                    tempAlert.present();
                }
            }
            this.changeDetectorRef.markForCheck();
            this.changeDetectorRef.detectChanges();
            if(success){
                success(this);
            }
        });
    };

    /**
     * 构建当前编辑历史
     */
    createEditHistory():any[]{
        let editHistory=[];
        if(this.process!=null){
            for(var ikey in this.process){
                var iprocess=this.process[ikey];
                if(iprocess!=null && iprocess.singleTask!=null 
                    && iprocess.singleTask.length>0){
                        
                        for(var j=0;j<iprocess.singleTask.length;j++){
                            var jitem=iprocess.singleTask[j];
                            if(jitem!=null && jitem.editRow!=null && jitem.userEdit){
                                editHistory.push(jitem.editRow);
                            }
                        }
                }else if(iprocess!=null && iprocess.editRow!=null && iprocess.userEdit){
                    editHistory.push(iprocess.editRow);
                }
            }
        }
        return editHistory;
    }

     /**
     * 项目提交通过到下一个环节
     */
    sendBack(sn: string,success:Function,error:Function){
        if(this.isOpting){
            this.alert.create({
                title:"系统提示",
                subTitle:"数据正在处理中，请稍后！",
                buttons:["确定"]
              }).present();
              return ;
        }
        if(sn==null){
            sn=this.sn;
        }
        this.isOpting=true;
        this.optback.editHistory=[];
        this.optback.editHistory=this.createEditHistory();
        this.dataService.sendBack(sn,this.optback,this.editRow,this.user).subscribe((data)=>{
            this.isOpting=false;
            if(data.status){
                if(data.entity!=null){
                    data.entity[this.isNew]=false;
                    this.editRow= data.entity;
                   // delete data.entity;
                }
                this.changeDetectorRef.markForCheck();
                this.changeDetectorRef.detectChanges();
                if(success){
                    success(this);
                }
                this.goHome();
            }else{
                if(error){
                    error(); 
                }else{
                    this.alert.create({
                        title:"系统提示",
                        subTitle:"退回失败，请重试！",
                        buttons:["确定"]
                      }).present();
                }
            }
        });
    };
}